import { memo, useCallback, useEffect, useRef, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Button, Drawer, Empty, Form, Input, message, Spin } from 'antd';
import {
  resAddDynamic,
  resChangeDynamic,
  resDeleteDynamic,
  resDynamicList,
  resUserDynamicList,
} from '@/services/dynamic';
import { userStore } from '@/store/userStore';
import { useInfiniteScroll, useRequest } from 'ahooks';
import QueueAnim from 'rc-queue-anim';
import { useRecoilValue } from 'recoil';
import { validateMessage } from '@/components/AddressFormModal';
import DynamicItem from '@/components/DynamicItem';
import NoMore from '@/components/NoMore';
import ProfileContainer from '@/components/ProfileContainer';
import RichEdit from '@/components/RichEdit';
import { OpenAndOperation } from '@/pages/Profile/components/MySell';

const MyDynamicPage: FC<PropsWithChildren<{}>> = () => {
  const ref = useRef<HTMLDivElement>(null!);

  const user = useRecoilValue(userStore);

  const { data, loading, reload, loadingMore, noMore, mutate } =
    useInfiniteScroll<API.PaginationResult<API.DynamicStruct>>(
      (currentData) => {
        return resUserDynamicList(user.id, {
          pageSize: 10,
          current: Math.ceil(currentData?.list.length! / 10 || 0) + 1,
        });
      },
      {
        target: ref,
        isNoMore: (d) => {
          return !d || d?.list.length >= d?.total;
        },
        threshold: 100,
      }
    );

  const [open, setOpen] = useState<OpenAndOperation>({
    show: false,
    status: 'add',
  });
  const onOpenClose = () => {
    setOpen((preState) => ({ ...preState, show: false }));
  };

  const [form] = Form.useForm();

  const { loading: addDynamicLoading, runAsync: addDynamic } = useRequest(
    resAddDynamic,
    { manual: true }
  );
  const { loading: changeDynamicLoading, runAsync: changeDynamic } = useRequest(
    resChangeDynamic,
    { manual: true }
  );

  const submitThen = (content: string) => {
    message.success(content);
    setOpen((preState) => ({ ...preState, show: false }));
  };

  const onFinish = (value: API.AddDynamicParams) => {
    if (open.status === 'add') {
      addDynamic(value).then(() => {
        submitThen('添加动态成功');
        reload();
      });
      return;
    }
    if (open.status === 'edit') {
      open.defaultValue &&
        changeDynamic(open.defaultValue?.id, value).then(() => {
          submitThen('编辑动态成功');
          reload();
        });
    }
  };

  const extra = (
    <Button
      loading={addDynamicLoading}
      type={'primary'}
      onClick={() => {
        form.resetFields(['title', 'content']);
        setOpen((preState) => ({ ...preState, show: true, status: 'add' }));
      }}
    >
      新增
    </Button>
  );

  const onEdit = useCallback(
    (defaultValue: API.DynamicStruct) => {
      form.setFieldsValue({ ...defaultValue });
      setOpen(() => ({ defaultValue, show: true, status: 'edit' }));
    },
    [setOpen]
  );

  const onDelete = useCallback(
    (id: number) => {
      resDeleteDynamic(id).then(() => {
        message.success('删除成功');
        const list = data?.list.filter((value) => value.id !== id);
        // @ts-ignore
        mutate({ list, total: data?.total });
      });
    },
    [data, mutate]
  );

  return (
    <ProfileContainer title={'我的动态'} extra={extra} ref={ref}>
      <div className={'flex justify-center pt-8 cus-comment'}>
        <Spin spinning={loading}>
          {
            <div className={'space-y-8  w-[810px] mx-auto'}>
              {data && data?.list.length > 0
                ? data.list.map((value) => (
                    <DynamicItem
                      data={value}
                      onEdit={onEdit}
                      onDelete={onDelete}
                      key={value.id}
                    />
                  ))
                : null}
            </div>
          }
        </Spin>
      </div>
      {data && data.list.length > 0 && (
        <div className={'w-[75%]  pb-16 mx-auto '}>
          <NoMore loadingMore={loadingMore} noMore={noMore} />
        </div>
      )}
      {!loading && data && data.list.length === 0 && <Empty />}

      <Drawer
        title={open.status === 'add' ? '添加动态' : '编辑动态'}
        onClose={onOpenClose}
        open={open.show}
        placement={'top'}
        height={'82vh'}
        extra={
          <Button
            type={'primary'}
            onClick={() => {
              form.submit();
            }}
          >
            保存
          </Button>
        }
      >
        <div className={'w-[756px] mx-auto'}>
          <Form
            form={form}
            validateMessages={validateMessage}
            onFinish={onFinish}
          >
            <Form.Item name={'title'}>
              <Input placeholder={'动态标题'} />
            </Form.Item>
            <div className={'h-96'}>
              <RichEdit
                name={'content'}
                placeholder={'请输入动态内容'}
                className={'h-96'}
              />
            </div>
          </Form>
        </div>
      </Drawer>
    </ProfileContainer>
  );
};

export default memo(MyDynamicPage);
